package com.cortex.pineapple.view;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

import com.cortex.pineapple.PineAppleApplication;
import com.cortex.pineapple.R;
import com.cortex.pineapple.adapters.Header;
import com.cortex.pineapple.adapters.Item;
import com.cortex.pineapple.adapters.ItemListAdapter.OnDragItemListener;
import com.cortex.pineapple.database.DataBase;
import com.cortex.pineapple.database.DataBase.ACTION;
import com.cortex.pineapple.database.ActionOnDataBase;
import com.cortex.pineapple.database.DataBase.OnDataBaseActionStateChangedListener;
import com.cortex.pineapple.database.DataBase.OnDataBaseFinishedReadListener;
import com.cortex.pineapple.database.DbHelper;
import com.cortex.pineapple.database.SeasonQuerySearch;
import com.cortex.pineapple.database.VisitLink;
import com.cortex.pineapple.listener.DragDropView;
import com.cortex.pineapple.listener.DragDropView.OnStateChangedListener;
import com.cortex.pineapple.view.RowSearch.OnRunSearchListener;
import com.cortex.pineapple.view.RowSearch.OnTextChangedListener;
import com.cortex.pineapple.view.TimeLine.LEVEL_ZOOM;
import com.cortex.pineapple.view.TimeLine.OnClickVisitLink;
import com.cortex.pineapple.view.TimeLine.OnFinishedScrollListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;;

public class HistorySearchesView extends RelativeLayout 
implements OnDataBaseActionStateChangedListener,OnClickListener{

	private TimeLine timeLine;
	private RelativeLayout containerTimeLine;
	private BrowserView browser;
	private RowSearch historySearch;
	private ImageView extended;
	private ProgressBar waitHistorySearch;
	private ImageView zoomOut,zoomIn;
	private PineAppleApplication app;
	private DataBase dataBase;
	private boolean isSearchMode = false;
	private OnClickExtendedListener onClickExtendedListener;
	private OnClosedHistoryListener onClosedHistoryListener;
	private boolean isClearTimeLine = true;
	private boolean isMultiAction = false;


	public HistorySearchesView(Context context) {
		super(context);
		init();
	}
	public HistorySearchesView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	public HistorySearchesView(Context context, AttributeSet attrs,int style) {
		super(context, attrs,style);
		init();
	}
	private void init(){
		app = (PineAppleApplication) getContext().getApplicationContext();
		dataBase = app.getDataBase();
		LayoutInflater.from(getContext()).inflate(R.layout.view_history_searches, this);
		timeLine = (TimeLine)findViewById(R.id.timeLine);
		containerTimeLine = (RelativeLayout)findViewById(R.id.containerTimeLine);
		browser = (BrowserView)findViewById(R.id.browser);
		historySearch = (RowSearch)findViewById(R.id.historySearch);
		extended = (ImageView)findViewById(R.id.extended);
		zoomOut = (ImageView)findViewById(R.id.zoomOut);
		zoomIn = (ImageView)findViewById(R.id.zoomIn);
		waitHistorySearch = (ProgressBar)findViewById(R.id.waitHistorySearch);
		historySearch.registerSpeechQuery();
		initListeners();
	}
	private void initListeners(){		
		extended.setOnClickListener(this);
		zoomOut.setOnClickListener(this);
		zoomIn.setOnClickListener(this);
		setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int x = (int) event.getX();
				int y  = (int) event.getY();
				Rect rect = new Rect();
				browser.getHitRect(rect);
				if(rect.contains(x, y)){
					if(!isMultiAction){
						close();
						return false;
					}
				}
				return false;
			}
		});
		historySearch.setOnRunSearchListener(new OnRunSearchListener() {

			@Override
			public void search(String query) {
				isClearTimeLine = true;
				isSearchMode = true;
				ActionOnDataBase action = new ActionOnDataBase(ACTION.READ_SEASONS_BY_QUERY, HistorySearchesView.this);
				action.setQuery(query);
				dataBase.doAction(action);
			}
		});
		historySearch.setOnTextChangedListener(new OnTextChangedListener() {

			@Override
			public void textChanged(String query) {
				isClearTimeLine = true;
				ActionOnDataBase action;
				isSearchMode = query.isEmpty()?false:true;
				if(!query.isEmpty()){
					action = new ActionOnDataBase(ACTION.READ_SEASONS_BY_QUERY, HistorySearchesView.this);
					action.setQuery(query);
				}
				else{
					action = new ActionOnDataBase(ACTION.READ_LAST_SEASONS, HistorySearchesView.this);
					action.setLimit(10);
				}
				dataBase.doAction(action);
			}
		});
		timeLine.setOnClickVisitLink(new OnClickVisitLink() {

			@Override
			public void visitLinkClicked(VisitLink visitLink) {
				if(!browser.isShown()){
					browser.setAlpha(1.0f);
					browser.setVisibility(VISIBLE);
					ViewGroup.LayoutParams params = getLayoutParams();
					params.width = ViewGroup.LayoutParams.MATCH_PARENT;
					setLayoutParams(params);
					Animation aniBrowser = AnimationUtils.loadAnimation(getContext(), R.anim.push_left_in);
					browser.startAnimation(aniBrowser);
				}
				browser.loadUrl(visitLink.getUrl(),visitLink.getSectionsSelected());
				isMultiAction = true;
			}

			@Override
			public void visitLinkLongClicked(VisitLink visitLink) {
				dataBase.doAction(new ActionOnDataBase(ACTION.UPDATE_VISIT_LINK, visitLink));
				timeLine.notifyDataChanged();
			}
		});
		timeLine.setOnFinishedScrollListener(new OnFinishedScrollListener() {

			@Override
			public void finishedScroll(SeasonQuerySearch season) {
				if(!isSearchMode){
					isClearTimeLine = false;
					ActionOnDataBase action = new ActionOnDataBase(ACTION.READ_NEXT_SEASONS,HistorySearchesView.this);
					action.setTop((int) season.getId());
					action.setLimit(10);
					dataBase.doAction(action);
				}
			}
		});
		
		
		timeLine.setOnDragVisitLinkListener(new OnDragItemListener() {

			@Override
			public void startDragging(View dragView, int x, int y, Item item) {
				if(browser.getVisibility() != VISIBLE){
					browser.setAlpha(0.0f);
					browser.setVisibility(VISIBLE);
				}
			}
			@Override
			public void moveDragging(View dragView, int x, int y,  Item item) {
				Rect rect = new Rect();
				browser.getHitRect(rect);
				float alpha = rect.right/(float)x;
				browser.setAlpha(alpha);
				if(rect.contains(x, y)){
					browser.setAlpha(1.0f);
				}
			}
			@Override
			public void stopDragging(View dragView, int x, int y,  Item item) {
				Rect rect = new Rect();
				browser.getHitRect(rect);
				if(rect.contains(x, y)){
					if(item.getData() instanceof VisitLink){
						browser.loadUrl(((VisitLink)item).getUrl());
					}
					browser.setAlpha(1.0f);
				}
				else if(!browser.isPageLoaded()){
					browser.setVisibility(INVISIBLE);
				}
				else{
					browser.setAlpha(1.0f);
				}

			}
			
		});
	
	}
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.extended){
			browser.setVisibility(GONE);
			ViewGroup.LayoutParams params = getLayoutParams();
			params.width = timeLine.getWidth();
			setLayoutParams(params);
			if(onClickExtendedListener != null){
				onClickExtendedListener.onClick();
			}
			isMultiAction = true;
		}
		else if(v.getId() == R.id.zoomOut){
			LEVEL_ZOOM level;
			switch(timeLine.getLevel()){
			case REGULAR_ZOOM:
				level = LEVEL_ZOOM.ZOOM_OUT;
				break;
			case ZOOM_IN:
				level = LEVEL_ZOOM.REGULAR_ZOOM;
				break;
			case ZOOM_OUT:
			default:
				return;
			}
			timeLine.setLevel(level);
		}
		else if(v.getId() == R.id.zoomIn){
			LEVEL_ZOOM level;
			switch(timeLine.getLevel()){
			case REGULAR_ZOOM:
				level = LEVEL_ZOOM.ZOOM_IN;
				break;
			case ZOOM_OUT:
				level = LEVEL_ZOOM.REGULAR_ZOOM;
				break;
			case ZOOM_IN:
			default:
				return;
			}
			timeLine.setLevel(level);
		}
	}
	public void setOnClickExtendedListener(OnClickExtendedListener onClickExtendedListener) {
		this.onClickExtendedListener = onClickExtendedListener;
	}
	public void setOnClosedHistoryListener(OnClosedHistoryListener onClosedHistoryListener) {
		this.onClosedHistoryListener = onClosedHistoryListener;
	}
	public void show(){
		ActionOnDataBase action = new ActionOnDataBase(ACTION.READ_LAST_SEASONS, HistorySearchesView.this);
		action.setLimit(10);
		dataBase.doAction(action);
		browser.setVisibility(INVISIBLE);
		ViewGroup.LayoutParams params = getLayoutParams();
		params.width = ViewGroup.LayoutParams.MATCH_PARENT;
		setLayoutParams(params);
		if(!isShown()){
			clear();
			Animation aniBackground = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
			aniBackground.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
					setVisibility(VISIBLE);

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation animation) {

				}
			});
			startAnimation(aniBackground);
			Animation aniTimeLine = AnimationUtils.loadAnimation(getContext(), R.anim.push_right_in);
			aniTimeLine.setStartOffset(300);
			containerTimeLine.startAnimation(aniTimeLine);
			if(browser.isShown()){
				Animation aniBrowser = AnimationUtils.loadAnimation(getContext(), R.anim.push_left_in);
				aniBrowser.setStartOffset(300);
				browser.startAnimation(aniBrowser);
			}
		}
	}

	public void show(String query){
		historySearch.setValue(query);
	}

	private void buildTimeLine(List<SeasonQuerySearch> seasons){
		if(!seasons.isEmpty()){
			if(isClearTimeLine){
				timeLine.clear();
			}
			List<Header> headers = new ArrayList<Header>();
			headers.addAll(seasons);
			timeLine.buildAdapter(headers);
		}
		else{
			Toast.makeText(getContext(), getResources().getString(R.string.noResults), Toast.LENGTH_SHORT).show();
		}
	}
	public void close(){
		if(isShown()){
			Animation aniTimeLine = AnimationUtils.loadAnimation(getContext(), R.anim.push_right_out);
			containerTimeLine.startAnimation(aniTimeLine);
			if(browser.isShown()){
				Animation aniBrowser = AnimationUtils.loadAnimation(getContext(), R.anim.push_left_out);
				browser.startAnimation(aniBrowser);
			}
			Animation aniBackground = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out);
			startAnimation(aniBackground);
			aniBackground.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onAnimationEnd(Animation animation) {
					setVisibility(GONE);
					if(onClosedHistoryListener != null){
						onClosedHistoryListener.onClosed();
					}
				}
			});
		}
	}
	public void notifyDataChanged(){
		invalidate();
		timeLine.notifyDataChanged();
	}
	public void clear(){
		historySearch.clear();
		timeLine.clear();
	}
	public interface OnClickExtendedListener{
		void onClick();
	}
	public interface OnClosedHistoryListener{
		void onClosed();
	}
	@Override
	public void finishedAction(List<SeasonQuerySearch> seasons) {
		waitHistorySearch.setVisibility(GONE);
		buildTimeLine(seasons);
	}
	@Override
	public void startAction(ACTION action) {
		waitHistorySearch.setVisibility(VISIBLE);
	}
	@Override
	public void cancelledAction(String message) {
		// TODO Auto-generated method stub

	}

}
